package com.xx.cloud.pay.config;

import cn.hutool.core.lang.UUID;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * file工具
 */
public class FileUtils {

	/**
	 * 将MultipartFile转为File
	 * @param mulFile
	 * @return
	 */
	public static File multipartFileToFile(MultipartFile mulFile) throws IOException {
		InputStream ins = mulFile.getInputStream();
		String fileName = mulFile.getOriginalFilename();
		String prefix = getFileNameNoEx(fileName)+ UUID.fastUUID();
		String suffix = "."+getExtensionName(fileName);
		File toFile = File.createTempFile(prefix,suffix);
		OutputStream os = new FileOutputStream(toFile);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
		return toFile;
	}

	/**
	 * 获取文件扩展名
	 *
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 获取不带扩展名的文件名
	 *
	 */
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}



	/**
	 * 请求图片地址, 返回的结果进行base64编码
	 * @param imgUrl 图片地址
	 * @return
	 */
	public static String requestUrlToBase64(String imgUrl) {
		String result = null;
		HttpURLConnection connection = null;

		try {
			URL url = new URL(imgUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 获取请求输入流
			InputStream inputStream = connection.getInputStream();
			// inputStream流数据转ByteArrayOutputStream
			int len = -1;
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			while ((len = inputStream.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}

			// ByteArrayOutputStream编码成base64字符串
			result = new String(Base64.getEncoder().encode(out.toByteArray()));
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(connection != null){
				connection.disconnect();
			}
		}

		return result;
	}

	/**
	 * 网络地址转换流
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static InputStream  urlToInputStream(String url) throws IOException {
		URL data = new URL(url);
		InputStream inputStream = data.openStream();
		return inputStream;
	}
}
